package ext.acae2.util;

import org.apache.log4j.Logger;

import wt.doc.WTDocument;
import wt.epm.EPMDocument;
import wt.fc.QueryResult;
import wt.fc.WTObject;
import wt.inf.container.WTContained;
import wt.load.LoadServerHelper;
import wt.log4j.LogR;
import wt.part.WTPart;
import wt.pom.PersistenceException;
import wt.series.MultilevelSeries;
import wt.series.Series;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.Iterated;
import wt.vc.IterationIdentifier;
import wt.vc.Mastered;
import wt.vc.VersionControlHelper;
import wt.vc.VersionControlServerHelper;
import wt.vc.VersionIdentifier;
import wt.vc.Versioned;
import wt.vc.config.LatestConfigSpec;

public class VersionUtil {
    private static final Logger LOGGER = LogR.getLogger(VersionUtil.class.getName());
	
	public static boolean isNewVersion(WTObject obj, String version) throws WTException
	{
		LOGGER.debug("> Start isNewVersion");
		
		boolean flag = true;
		if (version == null) {
			flag = false;
		} else if (obj instanceof WTPart) {
			if (version.equals(VersionControlHelper.getVersionIdentifier((WTPart) obj).getValue())) 
			flag = false;
		} else if (obj instanceof WTDocument) {
			if (version.equals(VersionControlHelper.getVersionIdentifier((WTDocument) obj).getValue())) 
			flag = false;
		} else if (obj instanceof EPMDocument) {
			if (version.equals(VersionControlHelper.getVersionIdentifier((EPMDocument) obj).getValue())) 
			flag = false;
		}
		
		LOGGER.debug("> End isNewVersion");
		
		return flag;
	}
	
	public static boolean isNewIteration(WTObject obj, String iteration) throws WTException
	{
		LOGGER.debug("> Start isNewIteration");
		
		boolean flag = true;
		if (iteration == null) {
			flag = false;
		} else if (obj instanceof WTPart) {
			if (iteration.equals(((WTPart) obj).getIterationIdentifier().getValue())) 
			flag = false;
		} else if (obj instanceof WTDocument) {
			if (iteration.equals(((WTDocument) obj).getIterationIdentifier().getValue())) 
			flag = false;
		} else if (obj instanceof EPMDocument) {
			if (iteration.equals(((EPMDocument) obj).getIterationIdentifier().getValue())) 
			flag = false;
		}
		
		LOGGER.debug("> End isNewIteration");
		
		return flag;
	}
	
	public static void setIteration(Iterated the_iterated, String iteration) throws WTException
	{
		LOGGER.debug("> Start setIteration");
		
		try
		{
			if (iteration != null)
			{
				Series ser = Series.newSeries("wt.vc.IterationIdentifier", iteration);
				IterationIdentifier iid = IterationIdentifier.newIterationIdentifier(ser);
				VersionControlHelper.setIterationIdentifier(the_iterated, iid);
			}
		}
		catch (WTPropertyVetoException e)
		{
			LoadServerHelper.printMessage("\nsetIteration: " + e.getMessage());
			e.printStackTrace();
			throw new WTException(e);
		}
		
		LOGGER.debug("> End setIteration");
	}
	
	public static void setVersion(Versioned the_versioned, String version) throws WTException
	{
		LOGGER.debug("> Start setVersion");
		
		try
		{
			if (version == null || version.trim().length() == 0)
			{
				// If the version ID string is null then the load file did not specify it.
				version = null;
				if (the_versioned.getVersionInfo() != null)
				// If the object already has a VersionInfo object then assume it is correct
				// and no further action is needed.  Otherwise, make a default VersionInfo object.
				return;
			}
			
			// Get the version series of the object.
			MultilevelSeries mls = null;
			final Mastered master = the_versioned.getMaster();
			if (master != null)
			{
				final String masterSeriesName = master.getSeries();
				if (masterSeriesName == null)
				{
					if (the_versioned instanceof WTContained && ((WTContained) the_versioned).getContainer() != null)
					{
						// Retrieve the series based on the OIR in effect for the container and object type/soft type.
						mls = VersionControlHelper.getVersionIdentifierSeries(the_versioned);
						wt.vc.VersionControlServerHelper.changeSeries(master, mls.getUniqueSeriesName());
					}
				}
				else
				{
					// Series name was already set in the master, just use it.
					mls = MultilevelSeries.newMultilevelSeries(masterSeriesName);
				}
			}
			if (mls == null)
			{
				// Unable to get the series from the master, just use the default series.
				mls = MultilevelSeries.newMultilevelSeries("wt.vc.VersionIdentifier", version);
			}
			
			if (version != null)
			{
				// Set the revision ID value if it was given in the load file.
				mls.setValueWithoutValidating(version.trim());
			}
			
			// Replace the default VID object (if there is one) with the correct one.
			VersionIdentifier vid = VersionIdentifier.newVersionIdentifier(mls);
			VersionControlServerHelper.setVersionIdentifier(the_versioned, vid, false /* validateIncreasing */);
		}
		catch (WTPropertyVetoException e)
		{
			LoadServerHelper.printMessage("\nsetVersion: " + e.getMessage());
			e.printStackTrace();
			throw new WTException(e);
		}
		catch (Exception e)
		{
			throw new WTException(e);
		}
		
		LOGGER.debug("> End setVersion");
	}

    public static WTObject getLatestObject(WTObject obj) throws PersistenceException, WTException {
        LOGGER.debug("> Start getLatestObject");
        
        QueryResult result = VersionControlHelper.service.allVersionsOf((Versioned) obj);
        result = new LatestConfigSpec().process(result);
        WTObject newObj = (WTObject) result.nextElement();
        
        LOGGER.debug("> End getLatestObject");
        return newObj;
    }
}
